<script setup>
import dayjs from 'dayjs';
// import { DatePicker as VCalendarDatePicker, VCalendar } from 'v-calendar'
useHead({
	title: 'HLS: Режим работы врачей',
})
definePageMeta({
	layout: "call",
})
const searchDoc = ref('');
const modalData = ref({});
// const docList = ref([]);
const errorRequest = ref(null);
const isOpen = ref(false);

async function setModalData(newData) {
	modalData.value = newData;
	isOpen.value = true;
	console.log("modal open")
}


const { data: docList, execute: docFetch } = useFetch(`http://192.168.100.48:8000/api/lab/rasp_all/`, {
	server: false,
	lazy: true,
})
const docFilter = computed(() => docList?.value?.graph_list?.filter((doctor) => (doctor?.fam.toUpperCase()).includes(searchDoc?.value.toUpperCase())))

watch(() => docFilter.value, () => {
	if (docFilter.value.length === 1) {
		modalData.value = docFilter.value[0]
		isOpen.value = true
	}
})

// async function fetchData() {
// 	fetch(toValue(`http://192.168.100.48:8000/api/lab/rasp_all/`), {
// 		mode: "cors",
// 	}).then((res) => res.json()).then((json) => (docList.value = json)).catch((err) => (errorRequest.value = err))
// 	// .then((response) => response.json()).then((json) => (docList.value = json)).catch((error) => (errorRequest.value = error))
// }

// onMounted(() => {
// 	fetchData()
// })

// const updater = setInterval(() => docFetch(), 1000 * 60 * 2)
// setInterval(() => docFetch(), 1000 * 60 * 1)

defineShortcuts({
	escape: {
		usingInput: true,
		whenever: [isOpen],
		handler: () => {
			isOpen.value = false
			searchDoc.value = ''
		}
	}
})

// onMounted(() => {
// 	setInterval(() => {
// 		// Your interval logic here
// 	}, 1000 * 60 * 1)
// })
// onBeforeUnmount(() => {
// 	clearInterval(updater.value)
// })
// onUnmounted(() => {
// 	clearInterval(updater.value);
// });

function closeModal() {
	isOpen.value = false
	searchDoc.value = ''
}
// function openModal() {
// 	isOpen.value = true
// }

const connection = new WebSocket("ws://127.0.0.1:8000/ws/chat/")


onMounted(() => {
	connection.onmessage = function (e) {
		console.log(e.data)
	}
})

</script>

<template>
	<div class="px-2">
		<ClientOnly>
			<div v-if="errorRequest">{{ errorRequest }}</div>
			<div>
				<div class="">
					<input v-model="searchDoc"
						class=" fixed top-1 sticky-header shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
						placeholder="Введите фамилию врача..." />
					<div v-auto-animate>
						<div v-for="value in docFilter" :key="value.doc" @click="setModalData(value)">
							<div class="flex flex-row flex-nowrap gap-4 text-left text-lg p-1 border border-1 border-slate-400"
								:class="[value.is_unwork ? 'bg-red-400' : value.is_unwork_soon ? 'bg-yellow-400' : '']">
								<div class="basis-4/12 self-center ">{{ value.fam }} {{ value.im }} {{ value.ot }}
								</div>
								<div class="basis-3/12 self-center ">{{ value.nspz }}</div>
								<div class="basis-2/12 self-center text-center ">{{ value.is_unwork ?
									value.rsn_unwork : "Работает"
									}}</div>
								<div class="basis-3/12 self-center text-center ">{{ value.nslp }}</div>
							</div>
						</div>
					</div>
				</div>
			</div>

			<UModal v-model="isOpen" :ui="{ base: 'max-w-6xl', width: '' }" close>
				<UCard :ui="{
					base: 'h-full flex flex-col',
					rounded: '',
					divide: 'divide-y divide-gray-100 dark:divide-gray-800',
					body: {
						base: 'grow'
					}
				}">
					<template #header>
						<div class="flex items-center justify-between">
							<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
								<div>{{ modalData.fam }} {{ modalData.im }} {{ modalData.ot }}</div>
							</h3>
							<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
								@click="closeModal" />
						</div>
					</template>
					<div class="mt-2">
						<div>{{ modalData.nspz }}</div>
						<div>{{ modalData.nslp }}</div>
						<div class="" :class="[new Date().getDate() % 2 === 0 ? 'bg-green-400' : '']">Четные
							дни
							{{
								modalData.even_day }}
						</div>
						<div class="" :class="[new Date().getDate() % 2 !== 0 ? 'bg-green-400' : '']">
							Нечетные
							дни {{
								modalData.noeven_day }}
						</div>
						<div v-if="modalData.is_unwork" class="flex flex-row">
							<div class="text-red-500">Не работает: {{ modalData.rsn_unwork }}</div>

							<div class="px-1 text-red-500">{{ modalData.date2_unwork &&
								(modalData.date2_unwork
									!==
									modalData.date1_unwork) ?
								`с ${dayjs(modalData.date1_unwork).format('DD.MM.YYYY')} по
								${dayjs(modalData.date2_unwork).format('DD.MM.YYYY')}` :
								dayjs(modalData.date1_unwork).format('DD.MM.YYYY') }}</div>
						</div>
						<div v-else class="text-green-500">
							Сегодня работает
						</div>
						<div v-for=" period in modalData.unwork " :key="period.iblc">
							<div v-if="period.cast != modalData.date1_unwork || period.cast1 != modalData.date2_unwork"
								class="text-red-500">Следующий нерабочий период: {{
									period.nrsn_ }} с {{
									dayjs(period.cast).format('DD.MM.YYYY') }} по {{
									dayjs(period.cast1).format('DD.MM.YYYY') }}</div>
						</div>
						<!-- <div class="flex flex-row">
						<div v-if="modalData.is_unwork">
							<VCalendar :attributes="[{
								highlight: 'red',
								dates: [[dayjs(modalData.date1_unwork), dayjs(modalData.date2_unwork)]]
							}]" borderless :disable-page-swipe="true" />
						</div>
						<div
							v-if="new Date(modalData.date2_unwork).getMonth() > new Date(modalData.date1_unwork).getMonth()">
							<VCalendar :attributes="[{
								highlight: 'red',
								dates: [[new Date(modalData.date1_unwork), new Date(modalData.date2_unwork)]]
							}]" borderless :initial-page="{ month: new Date(modalData.date2_unwork).getMonth() + 1, year: new Date(modalData.date2_unwork).getFullYear() }" />
						</div>
					</div> -->
						<div class="mt-4">
							<button type="button"
								class="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
								@click="closeModal">
								Закрыть
							</button>
						</div>
					</div>
				</UCard>
			</UModal>
		</ClientOnly>
	</div>
</template>
<style scoped>
.sticky-header {
	position: sticky;
	top: 0;
	background-color: white;
	/* или другой цвет фона */
	z-index: 49;
	/* чтобы обеспечить, что элемент находится над другими */
}
</style>